package com.fdb.basic.framework.core.validate;

import java.lang.reflect.Method;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import com.fdb.basic.framework.core.annotation.DicType;
import org.apache.commons.lang.IllegalClassException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @description:枚举类校验类
 * @date:2019年1月17日 下午5:21:22
 * @author:hengyh
 */
public class DicTypeValidatorImpl implements ConstraintValidator<DicType, String>{

	private static Logger logger = LoggerFactory.getLogger(DicTypeValidatorImpl.class);
	
	private Class<?> cls; // 枚举类对象
	private String method;
	@Override
	public void initialize(DicType constraintAnnotation) {
		cls = constraintAnnotation.dicType();
		method = constraintAnnotation.method();
	}

	@Override
	public boolean isValid(String value, ConstraintValidatorContext context) {
		try {
			if (!cls.isEnum()) {
				throw new IllegalClassException("DicType必须是Enum类型");
			}
			if (value == null || value.equals("")) {
				return true;
			}
			Method nameMethod = cls.getMethod(method);
			Object[] objs = cls.getEnumConstants();
			for (Object obj : objs) 
				if (value.equals(nameMethod.invoke(obj).toString())) 
					return true;
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return false;
	}

}
